// use in param2string
function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}
// object to query
export function param2string(json) {
  if (!json) return ''
  Object.keys(json).forEach(key => {
    if (!json[key] && json[key] !== 0) delete json[key]
  })
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

// 校验
// rules: {key: [{rquuired: true, message: 'keyCnName为必填'}, {validator: () => {}, message: 'keyCnName格式错误'}]}
export function customValid(validData, rules, cb) {
  // 错误信息存放
  const errorList = []
  Object.keys(rules).forEach(key => {
    rules[key].forEach(item => {
      const value = validData[key]
      if (item.required && !value) {
        errorList.push({ key, message: item.message})
        return
      }
      if (item.validator) {
        const validate = item.validator(value)
        if (!validate) {
          errorList.push({ key, message: item.message})
          return
        }
      }
    })
  })
  // 处理返回结果
  cb && cb(errorList)
  return errorList.length ? false : true
}
